package jwlee.testnetwork;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerDemo implements Runnable {
	ServerSocket serversocket;

	private int port = 8888;

	ServerDemo() {
	}

	ServerDemo(int port) {
		this.port = port;
	}

	/**
	 * 注意：Socket的发送与接收是需要同步进行的，即客户端发送一条信息，服务器必需先接收这条信息，
	 * 而后才可以向客户端发送信息，否则将会有运行时出错。?
	 */
	public static void main(String[] args) {
		new Thread(new ServerDemo(7777)).start();
		new Thread(new ServerDemo()).start();
	}

	public void run() {
		Socket socket = null;
		try {
			this.serversocket = new ServerSocket(this.port);
			this.serversocket.setSoTimeout(10000);// 设置10秒之后即认为超时

			// 服务器接收到客户端的数据后，创建与此客户端对话的Socket
			socket = this.serversocket.accept();

			// 用于接收客户端发来的数据的输入流
			DataInputStream dis = new DataInputStream(socket.getInputStream());
			// 用于向客户端发送数据的输出流
			DataOutputStream dos = new DataOutputStream(socket
					.getOutputStream());

			System.out.println("Message from Client：" + dis.readUTF());
			// 服务器向客户端发送连接成功确认信息
			dos.writeUTF("接受连接请求，连接成功!");
		} catch (IOException e) {
			e.printStackTrace();
			try {
				if (this.serversocket != null && !this.serversocket.isClosed()) {
					this.serversocket.close();
				}
				Thread.sleep(5000);// 关闭服务后睡眠5s.
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
	}
}
